package auditoryUIbk;
import java.io.*;
import java.text.DateFormat;
import java.util.*;
import fr.emn.utils.GeneralTimer;

/**
 * @author Shengdong Zhao
 * University of Toronto
 * mSpace Project
 *
 */
public class Logger {

	private String msFileName = "c:\\Temp\\logger.txt";
	private StringBuffer moLogText = new StringBuffer();
	public final static String msSeparator = "\t";
	static GeneralTimer hirestimer;
	static long starttime; 
	static {
		 hirestimer = new GeneralTimer();
		 starttime = (new Date()).getTime();
		 hirestimer.reset();
	}
	//private Date moTimeStamp = new Date();
	
	Logger(String fileName){
		msFileName = fileName;
		
		log("START_OF_SESSION", "---------------------------------------------------------");
	}

	public void log(String action, String text) {
		moLogText.append(
			action
				+ msSeparator
				+ text
				+ msSeparator
				+ getTime()
				+ "\n");
	}
	
	public static Logger createLogger(String file) {
		return new Logger(getLogFilename(file));
	}
	
	static String getLogFilename (String file) {
		Calendar calendar = new GregorianCalendar();
		DateFormat localFormat = DateFormat.getDateInstance();
		String date = localFormat.format(calendar.getTime());
		String DIR = "c:\\experimentLog\\" + date + "\\";
		(new File(DIR)).mkdirs();
		String filename = DIR + file + "_" + SimpleStrokeAudioUIbk.msUsrID + ".txt";
		return filename;		
	}

	public void flushText(String separatorMessage) {
		if (separatorMessage != null) {
			log(separatorMessage, "---------------------------------------------------------");
		}

		try {
			BufferedWriter out =
				new BufferedWriter(new FileWriter(msFileName, true));
			out.write(moLogText.toString());
//System.out.println(moLogText.toString());
			out.close();
			moLogText = new StringBuffer();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Exception happened when trying to open the buffer.");
		}
	}
	
	// hi-resolution time!
	public static long getTime() {
		return starttime + hirestimer.getIntTime();
	}
	
	public static String getTimeSinceExperimentStart() {
		int mn = (hirestimer.getIntTime()/1000)/60;
		int h = mn/60;
		mn -= h*60;
		String s;
		if (h > 0) s = "" + h; else s = "0";
		s += ":";
		if (mn > 0) s += ((mn<10)? "0" : "") + mn; else s+= "00";
		return s;
	}
}
